package com.xiyang.security.controller;

import com.xiyang.security.VO.ImgVO;
import com.xiyang.security.common.BaseResult;
import com.xiyang.security.common.ReturnCode;
import com.xiyang.security.utils.UUIDUtil;
import com.xiyang.security.utils.VerifyCodeUtil;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author xiyang.ycj
 * @since Jun 22, 2019 00:19:37 AM
 */
@RestController
public class MainController {


    @GetMapping(value = "/123")
    public Object login(){
        return "hello world";
    }

    @GetMapping("/getCode")
    public Object getCode(HttpServletRequest request) {

        /* 生成验证码字符串 */
        String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
        String uuid = UUIDUtil.GeneratorUUIDOfSimple();


        HttpSession session = request.getSession();
        session.setAttribute(uuid,verifyCode);

        int w = 111,h = 36;

        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            VerifyCodeUtil.outputImage(w, h, stream, verifyCode);
            return new BaseResult(ReturnCode.SUCCESS.getCode(), ReturnCode.SUCCESS.getMessage(),new ImgVO("data:image/gif;base64,"+ Base64Utils.encodeToString(stream.toByteArray()),uuid));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
